<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="关键字回复" name="first">
        <div class="filter-container">
          <el-button
            class="filter-item"
            type="primary"
            size="small"
            v-if="~accessable.indexOf('goods_brand:manage_add')"
            v-waves
            icon="el-icon-plus"
            @click="handleUpdate(null)"
          >添加回复</el-button>
          <el-input
            @keyup.enter.native="loadKwList"
            size="small"
            style="width: 200px;"
            class="filter-item"
            clearable
            placeholder="搜索关键字/规则名称"
            v-model="filters.kw"
          ></el-input>
          <el-button
            size="small"
            class="filter-item"
            type="primary"
            v-waves
            icon="el-icon-search"
            @click="loadKwList"
          >搜索</el-button>
        </div>
        <el-table
          :data="list"
          @sort-change="sortChange"
          v-loading="listLoading"
          element-loading-text="给我一点时间"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column prop="ruleName" align="center" label="规则名称" width="200">
            <template slot-scope="scope">
              <span>{{scope.row.ruleName}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="matchKey" align="center" label="关键词" width="200">
            <template slot-scope="scope">
              <span>{{scope.row.matchKey}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="matchContent" align="center" label="回复内容" width="320">
            <template slot-scope="scope">
              <span
                v-if="scope.row.replyContent && scope.row.replyContent.length"
              >{{scope.row.replyContent.length}} 个 回复</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="240" class="small-padding">
            <template slot-scope="scope">
              <!-- <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">详情</el-button> -->
              <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button
                type="info"
                v-if="scope.row.status==1"
                size="mini"
                @click="handleSetStatus(scope.row,0)"
              >停止</el-button>
              <el-button type="warning" v-else size="mini" @click="handleSetStatus(scope.row,1)">启用</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="filters.page"
            :page-sizes="[10,20,30,50]"
            :page-size="filters.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
        <el-dialog :title="isEditing?'修改回复':'添加回复'" :visible.sync="dialogFormVisible">
          <el-form
            class="dialog-form"
            :rules="rules"
            ref="dataForm"
            :model="temp"
            label-position="right"
            label-width="80px"
          >
            <el-form-item label="规则名称" prop="ruleName">
              <el-input v-model="temp.ruleName" placeholder="请输入规则名称"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="8">
                <el-form-item label="匹配模式" prop="matchMode">
                  <el-select v-model="temp.matchMode" placeholder="匹配模式">
                    <el-option
                      v-for="item in matchModels"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="16">
                <el-form-item label="关键词" prop="matchKey">
                  <el-input v-model="temp.matchKey" placeholder="请输入关键字"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="回复内容" prop="replyContent">
              <div v-if="temp.replyContent && temp.replyContent.length" class="reply-content-block">
                <div class="reply-content flex" v-for="(c,i) in temp.replyContent" :key="i">
                  <div v-if="c.type==0">{{c.value}} &nbsp;&nbsp;&nbsp;&nbsp;</div>
                  <div v-else>
                    <img :src="c.url" class="reply-cotent__img" alt />
                  </div>
                  <div class="flex-con" style="padding-left:30px;">
                    <el-button size="mini" type="text" @click="removeReplyContent(i)">删除</el-button>&nbsp;&nbsp;
                    &nbsp;&nbsp;
                    <el-button size="mini" @click="editReplyContent(c,i)" type="text">修改</el-button>
                  </div>
                </div>
              </div>
              <el-button
                size="mini"
                class="reply-content-btn"
                @click="addReplyContent"
                v-if="temp.replyContent.length<5"
                type="primary"
              >添加文本</el-button>
              <el-button
                size="mini"
                class="reply-content-btn"
                @click="addReplyImage"
                v-if="temp.replyContent.length<5"
                type="primary"
              >添加图片</el-button>
            </el-form-item>
            <el-form-item label="回复方式" prop="replyMode">
              <el-radio-group v-model="temp.replyMode">
                <el-radio
                  :label="item.value"
                  :key="item.value"
                  v-for="item in replyModes"
                >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
          </div>
        </el-dialog>
        <el-dialog
          :title="isEditingReply?'修改回复内容':'添加回复内容'"
          width="600px"
          :visible.sync="isAddReplying"
        >
          <el-input type="textarea" :rows="10" placeholder="请输入内容" v-model="currentReplyContent"></el-input>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isAddReplying = false">取消</el-button>
            <el-button type="primary" @click="saveReplyContent">确定</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="收到消息回复" name="second">
        <el-input type="textarea" :rows="10" placeholder="请输入回复内容" v-model="autoReplyContent"></el-input>
        <div class="btn-area">
          <el-button type="primary" :loading="isSavingSubscribe" @click="saveAutoReplyContent">保存</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="被关注回复" name="third">
        <el-input type="textarea" :rows="10" placeholder="请输入内容" v-model="subscribeContent"></el-input>
        <div class="btn-area">
          <el-button type="primary" :loading="isSavingSubscribe" @click="saveSubscribeContent">保存</el-button>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :visible.sync="isAddReplyingImage" title="选择图片" width="900px">
      <div class="dialog__header">
        <el-upload
          class="avatar-uploader"
          action="/wechat/material/upload-image"
          :show-file-list="false"
          :on-success="handleUploadImageSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-button size="small">上传图片</el-button>
        </el-upload>
      </div>
      <div class="dialog__content" v-loading="isLoadingImages">
        <div class="dialog__items">
          <div
            class="dialog__item"
            v-for="(item,itemIndex) in materialImages.items"
            :key="item.mediaId"
            @click="toggleSelectedItem(itemIndex)"
          >
            <img :src="item.url|proxyImg" class="dialog__item-img" alt />
            <div class="dialog__item-txt one-line">{{item.name}}</div>
            <div class="dialog__item-selected" v-if="itemIndex == currentSelectedImage">
              <img src="../../assets/reply/selected.png" alt class="dialog__item-selected-img" />
            </div>
          </div>
        </div>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange4Images"
          @current-change="handleCurrentChange4Images"
          :current-page.sync="materialImagesQueryParams.page"
          layout="total,prev, pager, next, jumper"
          :total="materialImages.totalCount"
        ></el-pagination>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddReplyingImage = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="currentSelectedImage==-1"
          @click="handleSelectMediaImage"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
.btn-area {
  padding-top: 30px;
}
.reply-cotent__img {
  width: 120px;
  height: 100px;
  object-fit: contain;
}
.dialog__header {
  display: flex;
  justify-content: flex-end;
  padding-bottom: 20px;
  border-bottom: 1px dashed #eee;
}
.filter-container {
  padding-top: 20px;
  margin-bottom: 0;
}
.reply-content {
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
  padding-top: 5px;
}
.reply-content-btn {
  margin-top: 5px;
}
.reply-content-block {
  padding-bottom: 15px;
}
.dialog__content {
  padding: 30px 0 0 10px;
}
.dialog__items {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.dialog__item {
  width: 120px;
  margin-right: 24px;
  border: 1px solid #e4e8eb;
  cursor: pointer;
  overflow: hidden;
  margin-bottom: 20px;

  position: relative;
}
.dialog__item:nth-of-type(6n) {
  margin-right: 0;
}
.dialog__item-selected-img {
  display: block;
  width: 30px;
}
.dialog__item-selected {
  position: absolute;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  right: 0;
  top: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
}
.dialog__item-img {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: contain;
}
.dialog__item-txt {
  text-align: center;
  white-space: nowrap;
  font-size: 12px;
  color: #999;
  text-overflow: ellipsis;
  overflow: hidden;
  padding: 5px 5px;
}
</style>
<script>
export default {
  data() {
    return {
      total: 0,
      filters: {
        page: 1,
        pageSize: 10
      },
      isAddReplyingImage: false,
      temp: {
        id: 0,
        matchKey: "",
        matchMode: 0,
        ruleName: "",
        replyMode: 1,
        replyContent: []
      },
      currentSelectedImage: -1,
      currentReplyContent: "",
      isLoadingImages: false,
      activeName: "first",
      subscribeContent: "",
      materialImagesQueryParams: {
        page: 1
      },
      materialImages: {
        items: [],
        itemCount: 0,
        totalCount: 0
      },
      isEditingReply: false,
      isAddReplying: false,
      matchModels: [
        {
          value: 0,
          label: "半匹配"
        },
        {
          value: 1,
          label: "全匹配"
        }
      ],
      replyModes: [
        {
          value: 0,
          label: "回复全部"
        },
        {
          value: 1,
          label: "随机回复一条"
        }
      ],
      autoReplyContent: "",
      isSavingSubscribe: false,
      rules: {
        ruleName: [
          {
            required: true,
            message: "规则名称不能为空"
          },
          {
            max: 60,
            message: "规则名不能为空且最多60个字"
          }
        ],
        matchKey: [
          {
            required: true,
            message: "关键词不能为空且最多30个字"
          },
          {
            max: 60,
            message: "关键词不能为空且最多30个字"
          }
        ],
        matchMode: [
          {
            required: true,
            message: "请选择匹配模式",
            type: "number"
          }
        ],
        replyMode: [
          {
            required: true,
            message: "请选择回复方式",
            type: "number"
          }
        ],
        replyContent: [
          {
            required: true,
            message: "回复内容不能为空",
            type: "array"
          }
        ]
      },
      isSavingAutoReplyContent: false
    };
  },
  created() {
    this.loadSubscribe();
    this.loadAutoReply();
    this.loadKwList();
  },
  filters: {
    proxyImg(v) {
      return process.env.h5Domain + "/proxy_wx_img/?v=11&url=" + v;
    }
  },
  methods: {
    proxyImg(v) {
      return process.env.h5Domain + "/proxy_wx_img/?v=11&url=" + v;
    },
    toggleSelectedItem(itemIndex) {
      this.currentSelectedImage = itemIndex;
    },
    handleUploadImageSuccess() {
      this.loadImageList();
    },
    handleCurrentChange(page) {
      this.filters.page = page;
      this.loadKwList();
    },
    loadKwList() {
      this.listLoading = true;
      this.$get("/wechat/wx-auto-reply/kw-reply/list", this.filters)
        .then(data => {
          this.list = data.records.map(el => {
            if (el.replyContent) {
              try {
                el.replyContent = JSON.parse(el.replyContent);
              } catch (e) {}
            } else {
              el.replyContent = [];
            }
            return el;
          });
          this.total = data.total;
          this.listLoading = false;
        })
        .catch(_ => {
          this.listLoading = false;
        });
    },
    handleSelectMediaImage() {
      if (this.isEditingReply) {
        const mediaItem = this.materialImages.items[this.currentSelectedImage];
        this.temp.replyContent[this.currentEditReplyIndex].value =
          mediaItem.mediaId;
        this.temp.replyContent[this.currentEditReplyIndex].url = this.proxyImg(
          this.materialImages.items[this.currentSelectedImage].url
        );
      } else {
        this.temp.replyContent.push({
          type: 1,
          url: this.proxyImg(
            this.materialImages.items[this.currentSelectedImage].url
          ),
          value: this.materialImages.items[this.currentSelectedImage].mediaId
        });
      }
      this.isAddReplyingImage = false;
    },
    saveReplyContent() {
      if (!this.currentReplyContent.trim()) {
        this.$message.error("回复内容不能为空");
        return;
      }
      if (this.isEditingReply) {
        this.temp.replyContent[
          this.currentEditReplyIndex
        ].value = this.currentReplyContent;
      } else {
        this.temp.replyContent.push({
          type: 0,
          value: this.currentReplyContent
        });
      }
      this.currentReplyContent = "";
      this.isAddReplying = false;
    },
    handleSetStatus(row, status) {
      this.$confirm(
        "确认" + (status == 0 ? "停用" : "启用") + "该记录吗？",
        "提醒",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        this.$post("/wechat/wx-auto-reply/kw-reply/update-status", {
          id: row.id,
          status
        }).then(() => {
          row.status = status;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
      });
    },
    handleSizeChange4Images(size) {},
    handleCurrentChange4Images(page) {
      this.materialImagesQueryParams.page = page;
      this.loadImageList();
    },
    loadImageList() {
      this.currentSelectedImage = -1;
      this.isLoadingImages = true;
      this.$get("/wechat/material/list", {
        type: "image",
        page: this.materialImagesQueryParams.page
      })
        .then(data => {
          this.isLoadingImages = false;
          this.materialImages = data;
        })
        .catch(() => {
          this.isLoadingImages = false;
        });
    },
    submitFormAction() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.submiting = true;
          const postData = Object.assign({}, this.temp);
          postData.replyContent = JSON.stringify(postData.replyContent);
          this.$post(
            "/wechat/wx-auto-reply/kw-reply/" +
              (this.isEditing ? "update" : "save"),
            postData
          )
            .then(_ => {
              this.$refs["dataForm"].clearValidate();
              this.loadKwList();
              this.submiting = false;
              this.$$notify();
              this.dialogFormVisible = false;
            })
            .catch(_ => {
              this.submiting = false;
            });
        }
      });
    },
    removeReplyContent(idx) {
      this.temp.replyContent.splice(idx, 1);
    },
    addReplyContent() {
      this.isAddReplying = true;
      this.isEditingReply = false;
    },
    addReplyImage() {
      if (!this.addReplyImageCalled) {
        this.addReplyImageCalled = true;
        this.loadImageList();
      }
      this.isAddReplyingImage = true;
      this.isEditingReply = false;
    },
    editReplyContent(item, idx) {
      if (item.type === 0) {
        this.isAddReplying = true;
      } else {
        this.isAddReplyingImage = true;
        this.currentSelectedImage = -1;
        if (!this.addReplyImageCalled) {
          this.addReplyImageCalled = true;
          this.loadImageList();
        }
      }
      this.isEditingReply = true;
      this.currentReplyContent = item.value;
      this.currentEditReplyIndex = idx;
    },
    handleClick(tab, event) {
      // console.log(tab, event)
    },
    saveAutoReplyContent() {
      if (this.isSavingAutoReplyContent) {
        return;
      }
      this.isSavingAutoReplyContent = true;
      this.$post("/wechat/wx-auto-reply/auto-reply/update", {
        replyContent: this.autoReplyContent
      })
        .then(_ => {
          this.$$notify("保存成功");
          this.isSavingAutoReplyContent = false;
        })
        .catch(_ => {
          this.isSavingAutoReplyContent = false;
        });
    },
    handleDelete(row) {
      this.$post("/wechat/wx-auto-reply/kw-reply/remove", { id: row.id }).then(
        _ => {
          this.loadKwList();
          this.$$notify();
        }
      );
    },
    saveSubscribeContent() {
      if (this.isSavingSubscribe) {
        return;
      }
      this.isSavingSubscribe = true;
      this.$post("/wechat/wx-auto-reply/subscribe-reply/update", {
        replyContent: this.subscribeContent
      })
        .then(_ => {
          this.$$notify("保存成功");
          this.isSavingSubscribe = false;
        })
        .catch(_ => {
          this.isSavingSubscribe = false;
        });
    },
    loadSubscribe() {
      this.$get("/wechat/wx-auto-reply/subscribe-reply/query").then(data => {
        this.subscribeContent = data.replyContent;
      });
    },
    loadAutoReply() {
      this.$get("/wechat/wx-auto-reply/auto-reply/query").then(data => {
        this.autoReplyContent = data.replyContent;
      });
    }
  }
};
</script>
